package com.adee.gulimall.product.service.impl;

import com.adee.gulimall.common.utils.PageUtils;
import com.adee.gulimall.common.utils.Query;
import com.adee.gulimall.product.dao.AttrGroupDao;
import com.adee.gulimall.product.entity.AttrGroupEntity;
import com.adee.gulimall.product.service.AttrGroupService;
import com.adee.gulimall.product.vo.SpuItemAttrGroupVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long categoryId) {

        // select * from pms_attr_group where catelog_id={categoryId}
        // [and (attr_group_id={key} or attr_group_name like {key})];
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");

        if(categoryId == 0) {
            if(!StringUtils.isEmpty(key)) {
                wrapper.eq("attr_group_id", key)
                        .or().like("attr_group_name", key);
            }
        } else {
            wrapper.eq("catelog_id", categoryId);
            if(!StringUtils.isEmpty(key)) {
                wrapper.and(obj -> {
                    obj.eq("attr_group_id", key)
                            .or().like("attr_group_name", key);
                });
            }
        }
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SpuItemAttrGroupVo> getAttrGroupWithAttrsBySpuId(Long spuId, Long catalogId) {
        List<SpuItemAttrGroupVo> list =
                baseMapper.getAttrGroupWithAttrsBySpuId(spuId, catalogId);

        return list;
    }

}